package cn.zyq.ykb.controller.mgt.system;


import cn.zyq.ykb.beans.sys.SysAdmin;
import cn.zyq.ykb.beans.sys.SysDept;
import cn.zyq.ykb.beans.sys.SysRole;
import cn.zyq.ykb.service.sys.SysAdminService;
import cn.zyq.ykb.service.sys.SysDeptService;
import cn.zyq.ykb.service.sys.SysPostService;
import cn.zyq.ykb.service.sys.SysRoleService;
import cn.zyq.ykb.system.annotation.Log;
import cn.zyq.ykb.system.common.BaseController;
import cn.zyq.ykb.system.common.PageParam;
import cn.zyq.ykb.system.exception.BusinessException;
import cn.zyq.ykb.system.ry.enums.BusinessType;
import cn.zyq.ykb.system.ry.security.handle.AjaxResult;
import cn.zyq.ykb.system.ry.util.SecurityUtils;
import cn.zyq.ykb.system.ry.util.StringUtils;
import cn.zyq.ykb.system.ry.util.poi.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息表
 * 2023-05-12 20:14:08
 */

@Api(tags = "用户信息表")
@RestController(value = "MgtSysAdminController")
@RequestMapping(value = "/mgt/sysAdmin")
public class SysAdminController extends BaseController {

    @Resource
    private SysAdminService sysAdminService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysDeptService deptService;

    @Autowired
    private SysPostService postService;
    //
    // @ApiOperation(value = "列表", response = SysAdmin.class)
    // @PostMapping(value = "/list")
    // public Object list(@RequestBody PageParam pageParam) {
    //     return this.sysAdminService.list(pageParam, this.getLoginAdmin());
    // }
    //
    // @ApiOperation(value = "添加")
    // @PostMapping(value = "/add")
    // public void add(@RequestBody SysAdmin param) {
    //     this.sysAdminService.add(param, this.getLoginAdmin());
    // }
    //
    // @ApiOperation(value = "修改")
    // @PostMapping(value = "/update")
    // public void update(@RequestBody SysAdmin param) {
    //     this.sysAdminService.update(param, this.getLoginAdmin());
    // }
    //
    // @ApiOperation(value = "详情", response = SysAdmin.class)
    // @GetMapping(value = "/detail/{serviceID}")
    // public Object detail(@PathVariable(value = "serviceID") String serviceID) {
    //     return this.sysAdminService.detail(serviceID, this.getLoginAdmin());
    // }
    //
    // @ApiOperation(value = "删除")
    // @DeleteMapping(value = "/del/{serviceID}")
    // public void del(@PathVariable(value = "serviceID") String serviceID) {
    //     this.sysAdminService.del(serviceID, this.getLoginAdmin());
    // }

    /**
     * 获取用户列表
     */
    // @PreAuthorize("@ss.hasPermi('system:user:list')")
    @PostMapping("/list")
    public Object list(@RequestBody PageParam param) {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<SysAdmin> list = sysAdminService.selectUserList(param);
        return new PageInfo<>(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    // @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody PageParam param) {
        List<SysAdmin> list = sysAdminService.selectUserList(param);
        ExcelUtil<SysAdmin> util = new ExcelUtil<SysAdmin>(SysAdmin.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    // @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public Object importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysAdmin> util = new ExcelUtil<SysAdmin>(SysAdmin.class);
        List<SysAdmin> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = sysAdminService.importUser(userList, updateSupport, operName);
        return message;
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysAdmin> util = new ExcelUtil<SysAdmin>(SysAdmin.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    // @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public Object getInfo(@PathVariable(value = "userId", required = false) Integer userId) {
        sysAdminService.checkUserDataScope(userId);
        Map ajax = new HashMap();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysAdmin.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysAdmin sysUser = sysAdminService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getSysRoleID).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    // @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Object add(@Validated @RequestBody SysAdmin user) {
        if (!sysAdminService.checkUserNameUnique(user)) {
            throw new BusinessException("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !sysAdminService.checkPhoneUnique(user)) {
            throw new BusinessException("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !sysAdminService.checkEmailUnique(user)) {
            throw new BusinessException("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return sysAdminService.add(user, this.getLoginSysAdmin());
    }

    /**
     * 修改用户
     */
    // @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public Object edit(@Validated @RequestBody SysAdmin user) {
        sysAdminService.checkUserAllowed(user);
        sysAdminService.checkUserDataScope(user.getSysAdminID());
        if (!sysAdminService.checkUserNameUnique(user)) {
            throw new BusinessException("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !sysAdminService.checkPhoneUnique(user)) {
            throw new BusinessException("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !sysAdminService.checkEmailUnique(user)) {
            throw new BusinessException("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        return sysAdminService.update(user, this.getLoginSysAdmin());
    }

    /**
     * 删除用户
     */
    // @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public Object remove(@PathVariable Integer[] userIds) {
        if (ArrayUtils.contains(userIds, this.getSysAdminID())) {
            throw new BusinessException("当前用户不能删除");
        }
        return sysAdminService.deleteUserByIds(userIds);
    }

    /**
     * 重置密码
     */
    // @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public Object resetPwd(@RequestBody SysAdmin user) {
        sysAdminService.checkUserAllowed(user);
        sysAdminService.checkUserDataScope(user.getSysAdminID());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return sysAdminService.resetPwd(user);
    }

    /**
     * 状态修改
     */
    // @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public Object changeStatus(@RequestBody SysAdmin user) {
        sysAdminService.checkUserAllowed(user);
        sysAdminService.checkUserDataScope(user.getSysAdminID());
        user.setUpdateBy(this.getSysAdminID());
        return sysAdminService.updateUserStatus(user);
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{sysAdminID}")
    public Object authRole(@PathVariable("sysAdminID") Integer sysAdminID) {
        Map ajax = new HashMap();
        SysAdmin user = sysAdminService.selectUserById(sysAdminID);
        List<SysRole> roles = roleService.selectRolesByUserId(sysAdminID);
        ajax.put("user", user);
        ajax.put("roles", SysAdmin.isAdmin(sysAdminID) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    // @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public void insertAuthRole(Integer sysAdminID, Integer[] roleIds) {
        sysAdminService.checkUserDataScope(sysAdminID);
        sysAdminService.insertUserAuth(sysAdminID, roleIds);
    }

    /**
     * 获取部门树列表
     */
    // @PreAuthorize("@ss.hasPermi('system:user:list')")
    @PostMapping("/deptTree")
    public Object deptTree() {
        return deptService.selectDeptTreeList(new SysDept());
    }
}

